import fnmatch
import os
import time
from pathlib import Path

force_overwrite = True
ignored_folder_list = []

def update_directory_times_correctly(root_directory):
    """
    正确地递归更新目录时间戳：每个目录的时间戳基于其内部文件和直接子目录的最新时间。

    Args:
        root_directory (str): 要处理的根目录路径。
    """
    root_path = Path(root_directory)

    # 使用 topdown=False 进行自底向上的遍历（先处理最深层的子目录）
    for current_dir, subdirs, files in os.walk(root_path, topdown=False):
        subdirs[:] = [d for d in subdirs if
                   not any(fnmatch.fnmatch(d, pattern) for pattern in ignored_folder_list)]
        current_dir_path = Path(current_dir)
        latest_time_in_current_dir = 0.0  # 用于记录当前目录下的最新时间

        # 1. 检查当前目录下的所有文件
        for file in files:
            file_path = current_dir_path / file
            try:
                file_mtime = os.path.getmtime(file_path)
                if file_mtime > latest_time_in_current_dir:
                    latest_time_in_current_dir = file_mtime
            except OSError as e:
                print(f"警告：无法读取文件 {file_path} 的时间信息: {e}")
                continue

        # 2. 检查当前目录下的所有直接子目录
        # 由于是自底向上遍历，子目录的时间已经被更新为它们内部的最新时间
        for subdir in subdirs:
            subdir_path = current_dir_path / subdir
            try:
                subdir_mtime = os.path.getmtime(subdir_path)
                if subdir_mtime > latest_time_in_current_dir:
                    latest_time_in_current_dir = subdir_mtime
            except OSError as e:
                print(f"警告：无法读取子目录 {subdir_path} 的时间信息: {e}")
                continue

        # 3. 只有当确实找到了文件或子目录，或者目录本身时间不是最新时，才更新时间戳
        if latest_time_in_current_dir > 0:
            try:
                if force_overwrite:
                    os.utime(current_dir_path, (latest_time_in_current_dir, latest_time_in_current_dir))
                    print(f"已更新目录 '{current_dir_path}' 的时间戳为: {time.ctime(latest_time_in_current_dir)}")
                else:
                    current_dir_current_mtime = os.path.getmtime(current_dir_path)
                    # 只有当计算出的最新时间比目录当前时间更“新”时，才执行更新操作
                    if latest_time_in_current_dir > current_dir_current_mtime:
                        os.utime(current_dir_path, (latest_time_in_current_dir, latest_time_in_current_dir))
                        print(f"已更新目录 '{current_dir_path}' 的时间戳为: {time.ctime(latest_time_in_current_dir)}")
                    else:
                        print(f"目录 '{current_dir_path}' 的时间戳已是最新，无需更新。")
            except OSError as e:
                print(f"错误：无法更新目录 {current_dir_path} 的时间戳: {e}")
        else:
            # # 给所有空文件夹指定一个时间
            # human_readable_time = "2019-3-30 19:30:30"
            #
            # time_format = "%Y-%m-%d %H:%M:%S"
            # structured_time = time.strptime(human_readable_time, time_format)
            # timestamp = time.mktime(structured_time)
            # os.utime(current_dir_path, (timestamp, timestamp))
            print(f"目录 '{current_dir_path}' 下未发现任何文件或子目录，跳过处理。")


def main(target_dir):
    """主函数示例"""
    # target_dir = input("请输入要处理的目录路径（留空使用当前目录）: ").strip()
    # if not target_dir:
    #     target_dir = "."

    target_path = Path(target_dir)
    if not target_path.exists() or not target_path.is_dir():
        print(f"错误：路径 '{target_dir}' 不存在或不是一个有效目录。")
        return

    print(f"开始处理目录树: {target_path.absolute()}")
    print("采用自底向上方式更新，确保每个目录的时间戳基于其直接内容...")
    print("-" * 60)

    update_directory_times_correctly(target_path)

    print("-" * 60)
    print("处理完成。")


if __name__ == "__main__":
    targets = [
        r"D:\projects\demo-c",
        r"D:\projects\demo-golang",
        r"D:\projects\demo-h5",
        r"D:\projects\demo-java",
        r"D:\projects\pt-java"
    ]
    for target in targets:
        main(target)
    # target = r"D:\projects"
    # main(target)